<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="优惠券名称，可以和活动名称保持一致" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入优惠券名称，可以和活动名称保持一致"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否限定作用范围，false：不限定，true：限定。默认false" prop="specific">
        <el-input
          v-model="queryParams.specific"
          placeholder="请输入是否限定作用范围，false：不限定，true：限定。默认false"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="折扣值，如果是满减则存满减金额，如果是折扣，则存折扣率，8折就是存80" prop="discountValue">
        <el-input
          v-model="queryParams.discountValue"
          placeholder="请输入折扣值，如果是满减则存满减金额，如果是折扣，则存折扣率，8折就是存80"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用门槛，0：表示无门槛，其他值：最低消费金额" prop="thresholdAmount">
        <el-input
          v-model="queryParams.thresholdAmount"
          placeholder="请输入使用门槛，0：表示无门槛，其他值：最低消费金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最高优惠金额，满减最大，0：表示没有限制，不为0，则表示该券有金额的限制" prop="maxDiscountAmount">
        <el-input
          v-model="queryParams.maxDiscountAmount"
          placeholder="请输入最高优惠金额，满减最大，0：表示没有限制，不为0，则表示该券有金额的限制"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="获取方式：1：手动领取，2：兑换码" prop="obtainWay">
        <el-input
          v-model="queryParams.obtainWay"
          placeholder="请输入获取方式：1：手动领取，2：兑换码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始发放时间" prop="issueBeginTime">
        <el-date-picker clearable
          v-model="queryParams.issueBeginTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始发放时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束发放时间" prop="issueEndTime">
        <el-date-picker clearable
          v-model="queryParams.issueEndTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束发放时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="优惠券有效期天数，0：表示有效期是指定有效期的" prop="termDays">
        <el-input
          v-model="queryParams.termDays"
          placeholder="请输入优惠券有效期天数，0：表示有效期是指定有效期的"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券有效期开始时间" prop="termBeginTime">
        <el-date-picker clearable
          v-model="queryParams.termBeginTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择优惠券有效期开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="优惠券有效期结束时间" prop="termEndTime">
        <el-date-picker clearable
          v-model="queryParams.termEndTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择优惠券有效期结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="总数量，不超过5000" prop="totalNum">
        <el-input
          v-model="queryParams.totalNum"
          placeholder="请输入总数量，不超过5000"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="已发行数量，用于判断是否超发" prop="issueNum">
        <el-input
          v-model="queryParams.issueNum"
          placeholder="请输入已发行数量，用于判断是否超发"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="已使用数量" prop="usedNum">
        <el-input
          v-model="queryParams.usedNum"
          placeholder="请输入已使用数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="每个人限领的数量，默认1" prop="userLimit">
        <el-input
          v-model="queryParams.userLimit"
          placeholder="请输入每个人限领的数量，默认1"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="creater">
        <el-input
          v-model="queryParams.creater"
          placeholder="请输入创建人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新人" prop="updater">
        <el-input
          v-model="queryParams.updater"
          placeholder="请输入更新人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="机构id" prop="insId">
        <el-input
          v-model="queryParams.insId"
          placeholder="请输入机构id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动id" prop="bannerId">
        <el-input
          v-model="queryParams.bannerId"
          placeholder="请输入活动id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['marketing:coupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['marketing:coupon:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['marketing:coupon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['marketing:coupon:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券id" align="center" prop="id" />
      <el-table-column label="优惠券名称，可以和活动名称保持一致" align="center" prop="name" />
      <el-table-column label="优惠券类型，1：普通券。目前就一种，保留字段" align="center" prop="type" />
      <el-table-column label="折扣类型，1：满减，2：每满减，3：折扣，4：无门槛" align="center" prop="discountType" />
      <el-table-column label="是否限定作用范围，false：不限定，true：限定。默认false" align="center" prop="specific" />
      <el-table-column label="折扣值，如果是满减则存满减金额，如果是折扣，则存折扣率，8折就是存80" align="center" prop="discountValue" />
      <el-table-column label="使用门槛，0：表示无门槛，其他值：最低消费金额" align="center" prop="thresholdAmount" />
      <el-table-column label="最高优惠金额，满减最大，0：表示没有限制，不为0，则表示该券有金额的限制" align="center" prop="maxDiscountAmount" />
      <el-table-column label="获取方式：1：手动领取，2：兑换码" align="center" prop="obtainWay" />
      <el-table-column label="开始发放时间" align="center" prop="issueBeginTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.issueBeginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束发放时间" align="center" prop="issueEndTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.issueEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券有效期天数，0：表示有效期是指定有效期的" align="center" prop="termDays" />
      <el-table-column label="优惠券有效期开始时间" align="center" prop="termBeginTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.termBeginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券有效期结束时间" align="center" prop="termEndTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.termEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券配置状态，1：待发放，2：未开始   3：进行中，4：已结束，5：暂停" align="center" prop="status" />
      <el-table-column label="总数量，不超过5000" align="center" prop="totalNum" />
      <el-table-column label="已发行数量，用于判断是否超发" align="center" prop="issueNum" />
      <el-table-column label="已使用数量" align="center" prop="usedNum" />
      <el-table-column label="每个人限领的数量，默认1" align="center" prop="userLimit" />
      <el-table-column label="拓展参数字段，保留字段" align="center" prop="extParam" />
      <el-table-column label="创建人" align="center" prop="creater" />
      <el-table-column label="更新人" align="center" prop="updater" />
      <el-table-column label="机构id" align="center" prop="insId" />
      <el-table-column label="活动id" align="center" prop="bannerId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['marketing:coupon:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['marketing:coupon:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券的规则信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="couponRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="优惠券名称，可以和活动名称保持一致" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称，可以和活动名称保持一致" />
        </el-form-item>
        <el-form-item label="是否限定作用范围，false：不限定，true：限定。默认false" prop="specific">
          <el-input v-model="form.specific" placeholder="请输入是否限定作用范围，false：不限定，true：限定。默认false" />
        </el-form-item>
        <el-form-item label="折扣值，如果是满减则存满减金额，如果是折扣，则存折扣率，8折就是存80" prop="discountValue">
          <el-input v-model="form.discountValue" placeholder="请输入折扣值，如果是满减则存满减金额，如果是折扣，则存折扣率，8折就是存80" />
        </el-form-item>
        <el-form-item label="使用门槛，0：表示无门槛，其他值：最低消费金额" prop="thresholdAmount">
          <el-input v-model="form.thresholdAmount" placeholder="请输入使用门槛，0：表示无门槛，其他值：最低消费金额" />
        </el-form-item>
        <el-form-item label="最高优惠金额，满减最大，0：表示没有限制，不为0，则表示该券有金额的限制" prop="maxDiscountAmount">
          <el-input v-model="form.maxDiscountAmount" placeholder="请输入最高优惠金额，满减最大，0：表示没有限制，不为0，则表示该券有金额的限制" />
        </el-form-item>
        <el-form-item label="获取方式：1：手动领取，2：兑换码" prop="obtainWay">
          <el-input v-model="form.obtainWay" placeholder="请输入获取方式：1：手动领取，2：兑换码" />
        </el-form-item>
        <el-form-item label="开始发放时间" prop="issueBeginTime">
          <el-date-picker clearable
            v-model="form.issueBeginTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始发放时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束发放时间" prop="issueEndTime">
          <el-date-picker clearable
            v-model="form.issueEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束发放时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="优惠券有效期天数，0：表示有效期是指定有效期的" prop="termDays">
          <el-input v-model="form.termDays" placeholder="请输入优惠券有效期天数，0：表示有效期是指定有效期的" />
        </el-form-item>
        <el-form-item label="优惠券有效期开始时间" prop="termBeginTime">
          <el-date-picker clearable
            v-model="form.termBeginTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择优惠券有效期开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="优惠券有效期结束时间" prop="termEndTime">
          <el-date-picker clearable
            v-model="form.termEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择优惠券有效期结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="总数量，不超过5000" prop="totalNum">
          <el-input v-model="form.totalNum" placeholder="请输入总数量，不超过5000" />
        </el-form-item>
        <el-form-item label="已发行数量，用于判断是否超发" prop="issueNum">
          <el-input v-model="form.issueNum" placeholder="请输入已发行数量，用于判断是否超发" />
        </el-form-item>
        <el-form-item label="已使用数量" prop="usedNum">
          <el-input v-model="form.usedNum" placeholder="请输入已使用数量" />
        </el-form-item>
        <el-form-item label="每个人限领的数量，默认1" prop="userLimit">
          <el-input v-model="form.userLimit" placeholder="请输入每个人限领的数量，默认1" />
        </el-form-item>
        <el-form-item label="创建人" prop="creater">
          <el-input v-model="form.creater" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="更新人" prop="updater">
          <el-input v-model="form.updater" placeholder="请输入更新人" />
        </el-form-item>
        <el-form-item label="机构id" prop="insId">
          <el-input v-model="form.insId" placeholder="请输入机构id" />
        </el-form-item>
        <el-form-item label="活动id" prop="bannerId">
          <el-input v-model="form.bannerId" placeholder="请输入活动id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Coupon">
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon } from "@/api/marketing/coupon";

const { proxy } = getCurrentInstance();

const couponList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    type: null,
    discountType: null,
    specific: null,
    discountValue: null,
    thresholdAmount: null,
    maxDiscountAmount: null,
    obtainWay: null,
    issueBeginTime: null,
    issueEndTime: null,
    termDays: null,
    termBeginTime: null,
    termEndTime: null,
    status: null,
    totalNum: null,
    issueNum: null,
    usedNum: null,
    userLimit: null,
    extParam: null,
    creater: null,
    updater: null,
    insId: null,
    bannerId: null
  },
  rules: {
    name: [
      { required: true, message: "优惠券名称，可以和活动名称保持一致不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "优惠券类型，1：普通券。目前就一种，保留字段不能为空", trigger: "change" }
    ],
    discountType: [
      { required: true, message: "折扣类型，1：满减，2：每满减，3：折扣，4：无门槛不能为空", trigger: "change" }
    ],
    specific: [
      { required: true, message: "是否限定作用范围，false：不限定，true：限定。默认false不能为空", trigger: "blur" }
    ],
    discountValue: [
      { required: true, message: "折扣值，如果是满减则存满减金额，如果是折扣，则存折扣率，8折就是存80不能为空", trigger: "blur" }
    ],
    thresholdAmount: [
      { required: true, message: "使用门槛，0：表示无门槛，其他值：最低消费金额不能为空", trigger: "blur" }
    ],
    maxDiscountAmount: [
      { required: true, message: "最高优惠金额，满减最大，0：表示没有限制，不为0，则表示该券有金额的限制不能为空", trigger: "blur" }
    ],
    obtainWay: [
      { required: true, message: "获取方式：1：手动领取，2：兑换码不能为空", trigger: "blur" }
    ],
    termDays: [
      { required: true, message: "优惠券有效期天数，0：表示有效期是指定有效期的不能为空", trigger: "blur" }
    ],
    totalNum: [
      { required: true, message: "总数量，不超过5000不能为空", trigger: "blur" }
    ],
    issueNum: [
      { required: true, message: "已发行数量，用于判断是否超发不能为空", trigger: "blur" }
    ],
    usedNum: [
      { required: true, message: "已使用数量不能为空", trigger: "blur" }
    ],
    userLimit: [
      { required: true, message: "每个人限领的数量，默认1不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    updateTime: [
      { required: true, message: "更新时间不能为空", trigger: "blur" }
    ],
    creater: [
      { required: true, message: "创建人不能为空", trigger: "blur" }
    ],
    updater: [
      { required: true, message: "更新人不能为空", trigger: "blur" }
    ],
    insId: [
      { required: true, message: "机构id不能为空", trigger: "blur" }
    ],
    bannerId: [
      { required: true, message: "活动id不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询优惠券的规则信息列表 */
function getList() {
  loading.value = true;
  listCoupon(queryParams.value).then(response => {
    couponList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    type: null,
    discountType: null,
    specific: null,
    discountValue: null,
    thresholdAmount: null,
    maxDiscountAmount: null,
    obtainWay: null,
    issueBeginTime: null,
    issueEndTime: null,
    termDays: null,
    termBeginTime: null,
    termEndTime: null,
    status: null,
    totalNum: null,
    issueNum: null,
    usedNum: null,
    userLimit: null,
    extParam: null,
    createTime: null,
    updateTime: null,
    creater: null,
    updater: null,
    insId: null,
    bannerId: null
  };
  proxy.resetForm("couponRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加优惠券的规则信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCoupon(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改优惠券的规则信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["couponRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCoupon(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCoupon(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除优惠券的规则信息编号为"' + _ids + '"的数据项？').then(function() {
    return delCoupon(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('marketing/coupon/export', {
    ...queryParams.value
  }, `coupon_${new Date().getTime()}.xlsx`)
}

getList();
</script>
